package org.skydiveapp;

import org.skydiveapplibrary.ui.InterfaceManager;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.Constants;
import org.skydiveapplibrary.data.FreefallProfileType;
import org.skydiveapplibrary.data.SkydiveType;
import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.repository.SkydiveTypeRepository;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class SkydiveTypeEditActivity extends SherlockActivity
{
	// activity request codes
    private static final int REQUEST_SELECT_FREEFALL_PROFILE_TYPE = 0;
    private static final int REQUEST_NOTES = 1;

    // repository
    private SkydiveTypeRepository repository = new SkydiveTypeRepository(this);
    
    // data
    private boolean isEdit = false;
    private boolean isDualDisplay;
    private SkydiveType skydiveType;

    private OnClickListener freefallProfileTypeEditListener = new OnClickListener()
    {
	    @Override
	    public void onClick(View view)
	    {
            Intent intent = new Intent(SkydiveTypeEditActivity.this, FreefallProfileTypeSelectListActivity.class);
            if (skydiveType.getFreefallProfileType() != null)
            {
                    intent.putExtra(Constants.EXTRA_FREEFALL_PROFILE_TYPE, skydiveType.getFreefallProfileType().toString());
            }
            startActivityForResult(intent, REQUEST_SELECT_FREEFALL_PROFILE_TYPE);
	    }
    };
    private OnClickListener notesEditListener = new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Intent intent = new Intent(SkydiveTypeEditActivity.this, NotesEditActivity.class);
            intent.putExtra(Constants.EXTRA_NOTES, skydiveType.getNotes());
            startActivityForResult(intent, REQUEST_NOTES);
        }
    };
    private DialogInterface.OnClickListener deleteConfirmListener = new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface arg0, int arg1)
        {
            delete();
        }
    };
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	SettingsRepository settingsRepository = new SettingsRepository(this);
		if (settingsRepository.getUseLightTheme())
			super.setTheme(R.style.SkydiveAppTheme_Light_Transparent);
		
        super.onCreate(savedInstanceState);

        // load data
        loadData();
        
        // init ui
        initializeUI();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (requestCode == REQUEST_SELECT_FREEFALL_PROFILE_TYPE && resultCode == RESULT_OK)
        {
            String profileType = intent.getStringExtra(Constants.EXTRA_FREEFALL_PROFILE_TYPE);
            updateFreefallProfileType(profileType);
        }
        else if (requestCode == REQUEST_NOTES && resultCode == RESULT_OK)
        {
            String notes = intent.getStringExtra(Constants.EXTRA_NOTES);
            updateNotes(notes);
        }
    }
    
    private void loadData()
    {
        // set isEdit flag
        Bundle extras = getIntent().getExtras();
        isEdit = (extras != null && extras.containsKey(Constants.EXTRA_SKYDIVE_TYPE_ID));

        // determine add vs. edit
        if (isEdit)
        {
            // editing
            int id = getIntent().getExtras().getInt(Constants.EXTRA_SKYDIVE_TYPE_ID);
            skydiveType = repository.getSkydiveType(id);
        }
        else
        {
        	// adding
            skydiveType = new SkydiveType();
        }
    }
    
    private void initializeUI()
    {
        // show view
        setContentView(R.layout.skydive_type_edit_view);
        
        isDualDisplay = this.findViewById(R.id.phoneLayout) == null;
        
        // set header text
        String titleText = isEdit ? 
        				getResources().getString(R.string.skydive_type_edit_label) :
        				getResources().getString(R.string.skydive_type_new_label);
		InterfaceManager.getInstance().setSubtitleText(getSupportActionBar(), titleText);
				
		
        // set name
        EditText nField = (EditText)findViewById(R.id.SkydiveTypeNameField);
        nField.setText(skydiveType.getName());
        
        // set default
        CheckBox dField = (CheckBox)findViewById(R.id.SkydiveTypeDefaultField);
        dField.setChecked(skydiveType.isDefault());
        
        // set freefall profile type
        TextView profileTypeField = (TextView)findViewById(R.id.SkydiveTypeFreefallProfileField);
        profileTypeField.setText(skydiveType.getFreefallProfileType() == null ? "" :
                getString(skydiveType.getFreefallProfileType().getResourceId()));
        profileTypeField.setOnClickListener(freefallProfileTypeEditListener);
        
        // set notes
        TextView notesField = (TextView)findViewById(R.id.SkydiveTypeNotesField);
        notesField.setText(skydiveType.getNotes());
        notesField.setOnClickListener(notesEditListener);
    }
    
    private void showDeleteWarning()
    {
        // create alert dialog
    	AlertDialog.Builder builder = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.DialogStyle));
        builder.setMessage(R.string.skydive_type_delete_warning);
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setTitle(R.string.delete_confirmation);
        builder.setPositiveButton(R.string.yes_button, deleteConfirmListener);
        builder.setNegativeButton(R.string.no_button, null);
        AlertDialog dialog = builder.create();
        // show dialog
        dialog.show();
    }
    
    private void updateFreefallProfileType(String profileType)
    {
        // update profile type
        if (profileType == null)
            skydiveType.setFreefallProfileType(null);
        else
            skydiveType.setFreefallProfileType(FreefallProfileType.valueOf(profileType));
        
        // update ui
        TextView profileTypeField = (TextView)findViewById(R.id.SkydiveTypeFreefallProfileField);
        profileTypeField.setText(skydiveType.getFreefallProfileType() == null ? "" :
                getString(skydiveType.getFreefallProfileType().getResourceId()));
    }
    
    private void updateNotes(String notes)
    {
        // update aircraft
        skydiveType.setNotes(notes);
        
        // update ui
        TextView notesField = (TextView)findViewById(R.id.SkydiveTypeNotesField);
        notesField.setText(skydiveType.getNotes());
    }
    
    private void save()
    {
	    // set name
	    EditText nField = (EditText)findViewById(R.id.SkydiveTypeNameField);
	    skydiveType.setName(nField.getText().toString());
	    
        // set is default
        CheckBox hField = (CheckBox)findViewById(R.id.SkydiveTypeDefaultField);
        skydiveType.setDefault(hField.isChecked());
	    
	    // save
	    if (isEdit)
	    {
            repository.updateSkydiveType(skydiveType);
	    }
	    else
	    {
            repository.addSkydiveType(skydiveType);
	    }
	    
	    // finish
	    close();
    }
    
    private void delete()
    {
        // delete
        repository.deleteSkydiveType(skydiveType);
        
        // finish
        close();
    }
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getSupportMenuInflater();
    	inflater.inflate(R.menu.menu_save, menu);
        if (isEdit)
        	inflater.inflate(R.menu.menu_delete, menu);
        
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    	menu.findItem(R.id.menu_back).setVisible(isDualDisplay);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
		if (itemId == R.id.menu_save)
		{
			save();
			return true;
		}
		else if (itemId == R.id.menu_back)
		{
			close();
			return true;
		}
		else if (itemId == R.id.menu_delete)
		{
			showDeleteWarning();
			return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
    }
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
	}
}